<script setup>
	import $http from '@/utils/http'
	import { ref } from 'vue'
	import { useUserStoreHook } from '@/stores/modules/user'
	import { useToast } from 'wot-design-uni'
	import { imgTurnBase64 } from '@/utils/pkg'
	import { useMessage } from 'wot-design-uni'
	
	const message = useMessage()
	const useUserStore = useUserStoreHook()
	const toast = useToast()
	const src = ref('')
	const imgSrc = ref('')
	const show = ref(false)
	const dateBirth = ref('')
	
	const upUserList = ref([
		{ text: '昵称', upKey: false, code: 1 },
		{ text: '邮箱', upKey: false, code: 2 },
		{ text: '手机号', upKey: false, code: 3 },
		{ text: '出生日期', upKey: false, code: 4 },
		{ text: '密码', upKey: false, code: 5 },
	])
	
	// 初始化
	const init = () => {
		if(!useUserStore.userinfo.is_login) { return }
		upUserList.value.forEach((v, i) => {
			if(i === 0) {
				v.text = useUserStore.userinfo.nickname
			} else if(i === 1) {
				v.text = useUserStore.userinfo.email ? useUserStore.userinfo.email : '邮箱'
			} else if(i === 2) {
				v.text = useUserStore.userinfo.phone ? useUserStore.userinfo.phone : '手机号'
			} else if(i === 3) {
				v.text = useUserStore.userinfo.date_birth ? useUserStore.userinfo.date_birth : '出生日期'
				dateBirth.value = useUserStore.userinfo.date_birth ? useUserStore.userinfo.date_birth : '选择日期'
			}
		})
	}
	init()
	
	// 获取图片
	function upload() {
	  uni.chooseImage({
	    count: 1,
	    success: (res) => {
	      const tempFilePaths = res.tempFilePaths[0]
	      src.value = tempFilePaths
	      show.value = true
	    }
	  })
	}
	
	// 获取裁剪后的图片
	function handleConfirm(event) {
	  const { tempFilePath } = event
	  imgSrc.value = tempFilePath
	}
	
	// 取消裁剪
	function handleCancel(event) {
		toast.show('已取消')
	}
	
	// 点击修改
	const upAvatar = async () => {
		if(imgSrc.value === '') {
			toast.show('请选择和裁剪您的头像')
			return
		}
		
		// 将图片转Base64
		let turnBase64 = ''
		try{
			turnBase64 = await imgTurnBase64(imgSrc.value)
		}catch(e){
			toast.show('上传失败，请重新裁剪')
			return
		}
		
		// 请求上传Base64图片
		const res = await $http.request({
			url: `/up-avatar`,
			method: 'POST',
			header: {
				token: true
			},
			data: { id: useUserStore.userinfo.id, avatar: turnBase64 },
		})
		if(res.code !== 200) {
			toast.show({
				position: 'bottom',
				msg: res.msg
			})
			return
		}
		
		// 重新保存
		useUserStore.SET_AVATAR(res.data.avatar)
		toast.show({
			position: 'bottom',
			msg: res.msg
		})
	}
	
	// 点击显示修改
	const showUpData = (itme, index) => {
		if(itme.code === 5) {itme.text = ''}
		itme.upKey = !itme.upKey
	}
	
	// 取消修改
	const noUpUserData = (itme, index) => {
		if(itme.code === 5) {
			upUserList.value[index].text = '密码'
		}
		upUserList.value[index].upKey = false
	}
	
	// 选择出生日期
	const pickerDateBirthOn = (e) => {
		dateBirth.value = e.detail.value
	}
	
	// 修改用户信息
	function upUserData(itme, index) {
		const userId = useUserStore.userinfo.id
		if(itme.code !== 5 && itme.code !== 4) {
			message.confirm({
				title: '修改',
			  msg: '确定修改?',
			})
			.then(() => {
				upData(itme, index)
			})
			.catch(() => {
				upUserList.value[index].upKey = false
			})
			return
		} else if(itme.code === 4) {
			// 修改出生日期
			upDateBirth(index)
			upUserList.value[index].upKey = false
			return
		}
		// 修改密码
		upPassword(index)
	}
	
	// 修改资料
	const upData = async (itme, index) => {
		if(itme.code === 1) {
			await upNickname(itme, index)
		} else if(itme.code === 2) {
			await upEmail(itme, index)
		} else if(itme.code === 3) {
			await upPhone(itme, index)
		}
		upUserList.value[index].upKey = false
	}
	
	// 修改昵称
	const upNickname = async (itme, index) => {
		const res = await $http.request({
			url: `/up-nickname`,
			method: 'POST',
			header: {
				token: true
			},
			data: { id: useUserStore.userinfo.id, nickname: itme.text },
		})
		if(res.code !== 200) {
			toast.show({
				position: 'bottom',
				msg: res.msg
			})
			return
		}
		itme.text = res.data.nickname
		useUserStore.SET_NICKNAME(res.data.nickname)
	}
	
	// 修改邮箱
	const upEmail = async (itme, index) => {
		const res = await $http.request({
			url: `/up-email`,
			method: 'POST',
			header: {
				token: true
			},
			data: { id: useUserStore.userinfo.id, email: itme.text },
		})
		if(res.code !== 200) {
			toast.show({
				position: 'bottom',
				msg: res.msg
			})
			return
		}
		itme.text = res.data.email
		useUserStore.SET_EMAIL(res.data.email)
	}
	
	// 修改手机号
	const upPhone = async (itme, index) => {
		const res = await $http.request({
			url: `/up-phone`,
			method: 'POST',
			header: {
				token: true
			},
			data: { id: useUserStore.userinfo.id, phone: itme.text },
		})
		if(res.code !== 200) {
			toast.show({
				position: 'bottom',
				msg: res.msg
			})
			return
		}
		itme.text = res.data.phone
		useUserStore.SET_PHONE(res.data.phone)
	}
	
	// 修改密码
	const upPassword = async (index) => {
		message
			.prompt({
				title: '确定密码',
				inputValue: upUserList.value[index].text,
				inputPattern: /[a-z|0-9|A-Z]*/g
			})
			.then(async (resp) => {
				if(resp.value === '') {
					toast.show({
						position: 'bottom',
						msg: '未确定密码'
					})
					return
				}
				if(upUserList.value[index].text !== resp.value) {
					toast.show({
						position: 'bottom',
						msg: '密码不一致'
					})
					return
				}
				
				// 请求修改密码
				const res = await $http.request({
					url: `/up-password`,
					method: 'POST',
					header: {
						token: true
					},
					data: { id: useUserStore.userinfo.id, password: resp.value },
				})
				if(res.code !== 200) {
					toast.show({
						position: 'bottom',
						msg: res.msg
					})
					return
				}
				
				// 退出登录
				await requestClearUserData()
				upUserList.value[index].upKey = false
				upUserList.value[index].text = '密码'
				uni.navigateTo({
					url: `/pages/login/login`
				});
			}).catch((e) => {
				upUserList.value[index].upKey = false
				upUserList.value[index].text = '密码'
			})
	}
	
	// 修改出生日期
	const upDateBirth = async (index) => {
		if(upUserList.value[index].text === dateBirth.value) {
			toast.show({
				position: 'bottom',
				msg: '日期未改变'
			})
			return
		}
		message
			.confirm({
				msg: '确定修改出生日期?',
				title: '修改'
			})
			.then(async () => {
				// 请求修改出生日期
				const res = await $http.request({
					url: `/up-date-birth`,
					method: 'POST',
					header: {
						token: true
					},
					data: { id: useUserStore.userinfo.id, date_birth: dateBirth.value },
				})
				if(res.code !== 200) {
					toast.show({
						position: 'bottom',
						msg: res.msg
					})
					return
				}
				
				upUserList.value[index].text = res.data.date_birth
				useUserStore.SET_DATE_BIRTH(res.data.date_birth)
			}).catch(() => {
				upUserList.value[index].upKey = false
			})
	}
	
	// 修改密码后退出登录和清理用户信息
	const requestClearUserData = async () => {
		const res = await $http.request({
			url: `/login-out`,
			method: 'POST',
			header: {
				token: true
			},
			data: { id: useUserStore.userinfo.id },
		})
		if(res.code !== 200) {
			toast.show({
				position: 'bottom',
				msg: res.msg
			})
			return
		}
		useUserStore.SET_REMOVE()
	}
	
</script>

<template>
	<view class="set-user">
		<view class="up-avatar-box">
			<wd-img-cropper
			  v-model="show"
			  :img-src="src"
			  @confirm="handleConfirm"
			  @cancel="handleCancel"
			>
			</wd-img-cropper>
			<view class="profile">
			  <view v-if="!imgSrc" class="img" @click="upload">
			    <wd-icon name="fill-camera" custom-class="img-icon"></wd-icon>
			  </view>
			  <wd-img v-if="imgSrc" round width="155rpx" height="155rpx" :src="imgSrc" mode="aspectFit" custom-class="profile-img" @click="upload" />
			  <view class="up-avatar" @click="upAvatar">点击确定修改</view>
			</view>
		</view>
		<view class="up-user">
			<view class="up-user-list" v-for="(itme, index) in upUserList" :key="index">
				<view class="list-input-box" v-if="itme.upKey">
					<input
						v-if="itme.code !== 4"
						class="list-input"
						type="text" focus
						v-model="itme.text"
						:placeholder="itme.text" />
					<view class="list-cell-db" v-else>
						<picker
							mode="date"
							:value="dateBirth"
							@change="pickerDateBirthOn">
							<view class="list-cell-picker">{{dateBirth}}</view>
						</picker>
					</view>
					<wd-icon
						class="list-input-btn"
						name="close" size="40rpx"
						@click="noUpUserData(itme, index)"></wd-icon>
					<wd-icon
						class="list-input-btn list-input-btn-yes"
						name="check" size="45rpx" @click="upUserData(itme, index)"></wd-icon>
				</view>
				<view class="list-input-box" v-else>
					<text
						class="list-input-text"
						@click="showUpData(itme, index)">{{ itme.text }}</text>
					<wd-icon
						class="list-input-btn"
						name="edit" size="22px"
						@click="showUpData(itme, index)"></wd-icon>
				</view>
			</view>
		</view>

	</view>
	<wd-toast />
	<wd-message-box></wd-message-box>
</template>

<style scoped lang="scss">
@import "@/common/common.scss";
.set-user {
	width: 100%;
	
	display: flex;
	align-items: center;
	flex-direction: column;
	justify-content: center;
	
	.up-avatar-box {
		width: 90%;
		height: 300rpx;
		margin: 10rpx 0;
		border-radius: 10rpx;
		background-color: $all-box-bg-color;
		
		.profile {
			width: 100%;
			height: 100%;
			
			display: flex;
			align-items: center;
			flex-direction: column;
			justify-content: center;
			
			:deep(.img-icon) {
				width: 150rpx;
				height: 150rpx;
				border-radius: 50%;
				margin-top: 20rpx;
				background-color: #DDDDDD;
				
				display: flex;
				align-items: center;
				justify-content: center;
			}			
			.up-avatar {
				color:  #fff;
				font-size: 30rpx;
				margin: 20rpx 0;
			}
		}
	}
	.up-user {
		width: 90%;
		background-color: $all-box-bg-color;
		
		.up-user-list {
			width: 100%;
			height: 80rpx;
			border-bottom: 2rpx solid #5A5C61;
			
			.list-input-box {
				height: 100%;
				
				display: flex;
				align-items: center;
				justify-content: center;
				
				.list-input {
					width: 40%;
					height: 100%;
					color: #DDDDDD;
					font-size: 28rpx;
					padding: 0 20rpx;
					margin-left: 80rpx;
				}
				
				.list-cell-db {
					width: 60%;
					color: #DDDDDD;
					font-size: 28rpx;
					margin-left: 40rpx;
					
					display: flex;
					align-items: center;
					justify-content: center;
					
					.list-cell-picker {
						color: #DDDDDD;
						font-size: 28rpx;
						margin-left: 40rpx;
					}
				}
				
				.list-input-btn {
					color: #DDDDDD;
				}
				.list-input-btn-yes {
					color: #7a9aff;
					margin-left: 20rpx;
				}
				
				.list-input-text {
					color: #DDDDDD;
				}
			}
		}
	}
}
</style>
